package priv.mill.visiter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 依赖抽象而不依赖具体
 * 单一职责原则
 * 没有继承，而是用组合
 * 多个接口比一个接口更好--》
 * @author mill
 * @date 2018年1月8日
 * Main
 */
public class Main {

	public static void main(String[] args) {
		House house=new BieShu();
		house.zhuangXiu(new MuGong());
		house.zhuangXiu(new NiGong());
		house.zhuangXiu(new Ivisiter() {
			@Override
			public void doSomeThing(String key) {
				System.out.printf("i am is seef,i get %s,i will catch all variable thing\n",key);
			}
		});
		try {
			
			List<Map<String, Object>> lists=new ArrayList<Map<String,Object>>();
			test("select * from web_user",new SqlVisiter() {
				
				@Override
				public void handler(ResultSet executeQuery) throws SQLException {
					ResultSetMetaData metaData = executeQuery.getMetaData();
					while(executeQuery.next()){
						Map<String, Object> map=new HashMap<String, Object>();
						for (int i = 0; i < metaData.getColumnCount(); i++) {
							String columnLabel = metaData.getColumnLabel(i+1);
							map.put(columnLabel,executeQuery.getObject(i+1));
						}
						lists.add(map);
					}
				}
			});
			System.out.println(lists);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void test(String sql, SqlVisiter sqlVisiter) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		try(Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
				PreparedStatement prepareStatement = connection.prepareStatement(sql);
				ResultSet executeQuery = prepareStatement.executeQuery();
				){
			sqlVisiter.handler(executeQuery);
		}
	}
	
	
}
